package com.linxianqin.springbootVue.service.webService;

import com.linxianqin.springbootVue.domain.constant.CacheStants;
import com.linxianqin.springbootVue.domain.constant.Constants;
import com.linxianqin.springbootVue.domain.model.LoginBody;
import com.linxianqin.springbootVue.domain.model.LoginUser;
import com.linxianqin.springbootVue.manage.exception.CaptchaException;
import com.linxianqin.springbootVue.manage.exception.CaptchaExpireException;
import com.linxianqin.springbootVue.manage.exception.CustomException;
import com.linxianqin.springbootVue.manage.exception.UserPasswordNotMatchException;
import com.linxianqin.springbootVue.manage.Async.AsyncFactory;
import com.linxianqin.springbootVue.manage.Async.AsyncManager;
import com.linxianqin.springbootVue.service.CacheService;
import com.linxianqin.springbootVue.utils.MessageUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.Optional;

/**
 * 功能描述：用户登录业务类
 *
 * @author lxq
 * @version 1.00
 * @Date 2020/12/13
 */
@Slf4j
@Component
public class SysLoginService {
    @Resource
    private AuthenticationManager authenticationManager;
    private TokenService tokenService;
    private CacheService cacheService;
    public SysLoginService(TokenService tokenService, CacheService cacheService)
    {
        this.tokenService=tokenService;
        this.cacheService=cacheService;
    }
    /**
     * 登录验证
     * @param loginBody 用户登录信息
     * @return 结果
     */
    public String login(LoginBody loginBody)
    {
        String username=loginBody.getUsername();
        String password=loginBody.getPassword();
//        String code=loginBody.getCode();
//        String uuid=loginBody.getCode();
//        //验证码缓存的key
//        String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
//        //获取验证码
//        String captcha =Optional.ofNullable(cacheService.get(CacheStants.CAPTCHA_CACHE, verifyKey)).orElse("").toString();
//        //从缓存中移除验证码
//        cacheService.remove(CacheStants.CAPTCHA_CACHE,verifyKey);
//        if (captcha == null||"".equals(captcha))
//        {
//            //记录登录信息
//            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
//            throw new CaptchaExpireException();
//        }
//        if (!code.equalsIgnoreCase(captcha))
//        {
//            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
//            throw new CaptchaException();
//        }
        // 用户验证
        Authentication authentication = null;
        try {
            //该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager
                    .authenticate(new UsernamePasswordAuthenticationToken(username, password));
        }
        catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            } else {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new CustomException(e.getMessage());
            }
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        // 生成token
        return tokenService.createToken(loginUser);
    }
}
